<template>
  <div class="main-box">
    <TreeFilter
      label="name"
      id="_id"
      title="组织"
      :data="treeFilterData"
      :default-value="initParam.condition.orgId"
      @change="changeTreeFilter"
    />
    <div class="table-box">
      <ProTable
        ref="proTable"
        :indent="20"
        :highlight-current-row="true"
        row-key="_id"
        :columns="columns"
        :request-api="getTableList"
        :request-auto="false"
        :init-param="initParam"
      >
        <!-- 表格 header 按钮 -->
        <template #tableHeader>
          <el-button type="primary" :icon="CirclePlus" @click="openDrawer('新增')"> 新增 </el-button>
          <el-button type="primary" :icon="Download" plain @click="downloadFile">导出数据</el-button>
        </template>
        <!-- 表格操作 -->
        <template #operation="scope">
          <el-button type="primary" link :icon="View" @click="openDrawer('查看', scope.row)">查看</el-button>
          <el-button type="primary" link :icon="EditPen" @click="openDrawer('编辑', scope.row)">编辑</el-button>
          <el-button type="primary" link :icon="Delete" @click="deleteAccount(scope.row)">删除</el-button>
        </template>
      </ProTable>
      <UserDrawer ref="drawerRef" />
      <ImportExcel ref="dialogRef" />
    </div>
  </div>
</template>

<script setup lang="tsx" name="useProTable">
import { ref, reactive, onMounted } from "vue";
import { ExportObj, Users } from "@/api/types/base";
import { useHandleData } from "@/hooks/useHandleData";
import { ElMessageBox } from "element-plus";
import ProTable from "@/components/ProTable/index.vue";
import TreeFilter from "@/components/TreeFilter/index.vue";
import ImportExcel from "@/components/ImportExcel/index.vue";
import UserDrawer from "./userDrawer.vue";
import { ProTableInstance, ColumnProps } from "@/components/ProTable/interface";
import { CirclePlus, Delete, EditPen, Download, View } from "@element-plus/icons-vue";
import apiService from "@/api/services/apiService";
import { useDateFormat } from "@vueuse/core";
import { useDownload } from "@/hooks/useDownload";
import { ExportColType } from "@/enums/sysEnum";
// ProTable 实例
const proTable = ref<ProTableInstance>();

// 如果表格需要初始化请求参数，直接定义传给 ProTable (之后每次请求都会自动带上该参数，此参数更改之后也会一直带上，改变此参数会自动刷新表格数据)
const initParam = reactive({
  condition: { orgId: "" },
  options: { sort: { sort: 1 } }
});

const initVar = reactive({
  tbName: "users"
});

onMounted(() => {
  getTreeList();
});

// 如果你想在请求之前对当前请求参数做一些操作，可以自定义如下函数：params 为当前所有的请求参数（包括分页），最后返回请求列表接口
// 默认不做操作就直接在 ProTable 组件上绑定	:requestApi="getUserList"
const getTableList = (params: any) => {
  // let newParams = JSON.parse(JSON.stringify(params));
  return apiService.findPage("users", params.condition, params.options);
};

const treeFilterData = ref<any>([]);
const getTreeList = async () => {
  const { data } = await apiService.findTree("orgs", {}, { sort: { sort: 1 } });
  treeFilterData.value = data;
  initParam.condition.orgId = treeFilterData.value[0]._id;
};

// 树形筛选切换
const changeTreeFilter = (val: string) => {
  proTable.value!.pageable.pageNum = 1;
  initParam.condition.orgId = val;
};

// 表格配置项
const columns = reactive<ColumnProps<Users>[]>([
  { type: "index", label: " ", width: 85 },
  { prop: "userName", label: "用户名", search: { el: "input" } },
  { prop: "loginName", label: "登录名称" },
  {
    prop: "sex",
    label: "性别",
    // 字典请求携带参数
    enum: () => apiService.findClassify("SEX"),
    fieldNames: { label: "name", value: "value" }
  },
  {
    prop: "post",
    label: "岗位",
    // 字典请求携带参数
    enum: () => apiService.findClassify("user_post"),
    fieldNames: { label: "name", value: "value" }
  },
  { prop: "workNo", label: "工号" },
  {
    prop: "orgId",
    label: "所属组织",
    // 字典请求携带参数
    enum: treeFilterData,
    fieldNames: { label: "name", value: "_id" }
  },
  { prop: "sort", label: "序号" },
  {
    prop: "state",
    label: "状态",
    // 字典请求携带参数
    enum: () => apiService.findClassify("DATA_STATE"),
    search: { el: "select", props: { filterable: true } },
    fieldNames: { label: "name", value: "value" }
  },
  { prop: "operation", label: "操作", fixed: "right", width: 240 }
]);

// 删除信息
const deleteAccount = async (params: Users) => {
  await useHandleData(apiService.deleteById, "users", params._id, `删除用户【${params.userName}】`);
  proTable.value?.getTableList();
};

// 导出数据
const downloadFile = async () => {
  ElMessageBox.confirm("确认导出数据?", "温馨提示", { type: "warning" }).then(() =>
    useDownload(apiService.commonExport, `用户管理-${useDateFormat(new Date(), "YYYY-MM-DD").value}`, "", getExcelConfig(), false)
  );
};

const getExcelConfig = (): ExportObj => {
  let newParams = JSON.parse(JSON.stringify(proTable.value?.totalParam));
  return {
    params: newParams,
    tableName: initVar.tbName,
    keyPropName: "_id",
    enumTypes: ["SEX", "user_post", "DATA_STATE"],
    tableConfigs: [{ tableName: "orgs", fields: ["_id", "name"] }],
    header: [
      { header: "序号", width: 6, ext: { prop: "index", type: ExportColType.INDEX } },
      {
        header: "姓名",
        width: 8,
        ext: { prop: "userName", type: ExportColType.DEFAULT }
      },
      { header: "工号", width: 10, ext: { prop: "workNo", type: ExportColType.DEFAULT } },
      { header: "组织", width: 15, ext: { prop: "orgId", type: ExportColType.TABLE, key: "orgs" } },
      { header: "登录名称", width: 30, ext: { prop: "loginName", type: ExportColType.DEFAULT } },
      {
        header: "性别",
        width: 8,
        ext: { prop: "sex", type: ExportColType.ENUM, key: "SEX" }
      },
      {
        header: "岗位",
        width: 15,
        ext: { prop: "post", type: ExportColType.ENUM, key: "user_post" }
      },
      { header: "邮箱", width: 30, ext: { prop: "email", type: ExportColType.DEFAULT } },
      { header: "状态", width: 10, ext: { prop: "state", type: ExportColType.ENUM, key: "DATA_STATE" } }
    ]
  };
};

// 打开 drawer(新增、查看、编辑)
const drawerRef = ref<InstanceType<typeof UserDrawer> | null>(null);
const openDrawer = (title: string, row: Partial<Users> = {}) => {
  if (title.indexOf("新增") !== -1) {
    row.orgId = initParam.condition.orgId;
  }
  const params = {
    title,
    tbName: "users",
    isView: title === "查看",
    row: { ...row },
    api: title.indexOf("新增") !== -1 ? apiService.save : title === "编辑" ? apiService.updateById : undefined,
    getTableList: proTable.value?.getTableList
  };
  drawerRef.value?.acceptParams(params);
};
</script>
